<template>
  <div class="user">
    <!--部门数据-->
    <div v-sync-height="['.list', !loading, '.industry-layout-main']" class="tree">
      <div class="search">
        <el-input
          v-model="deptName"
          class="search-dep"
          placeholder="搜索"
          clearable
          size="small"
          prefix-icon="el-icon-search"
          style="width: 100%;"
        />
      </div>
      <div class="content">
        <el-tree
          ref="tree"
          :data="deptOptions"
          :props="defaultProps"
          accordion
          :expand-on-click-node="false"
          :filter-node-method="filterNode"
          highlight-current
          :default-expand-all="false"
          @node-click="handleNodeClick"
        >
        </el-tree>
      </div>
    </div>

    <!--用户数据-->
    <div class="list">
      <SearchWithOperate
        :form-options="formOptions"
        btn-items="add,delete,import,export"
        :add-permi="['system:user:add']"
        :delete-permi="['system:user:remove']"
        @onSearch="handleQuery"
        @onAdd="handleAdd"
        @onReset="resetQuery"
        @onDelete="handleDeleteAll"
        @onImport="handleImport"
        @onExport="handleExport"
      >
        <template v-slot:dateRange>
          <el-date-picker
            v-model="dateRange"
            style="width: 200px"
            value-format="yyyy-MM-dd"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </template>
      </SearchWithOperate>

      <el-table
        v-loading="loading"
        tooltip-effect="light"
        :data="userList"
        border
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" align="center" />
        <el-table-column v-if="columns[0].visible" key="userId" label="用户编号" prop="userId" />
        <el-table-column v-if="columns[1].visible" key="userName" label="用户账号" prop="userName" show-overflow-tooltip />
        <el-table-column v-if="columns[2].visible" key="nickName" label="用户姓名" prop="nickName" show-overflow-tooltip />
        <el-table-column v-if="columns[3].visible" key="deptName" label="部门" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-row v-for="(item,index) in scope.row.depts" :key="index">{{ item.deptName }}</el-row>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns[4].visible"
          key="phonenumber"
          label="手机号码"
          align="center"
          prop="phonenumber"
          show-overflow-tooltip
        />
        <el-table-column v-if="columns[5].visible" key="status" label="状态" width="70" align="center">
          <template slot-scope="scope">
            <span class="stateShell">
              <div v-if="scope.row.status==='0'" class="common-prompt" style="background-color:#67C23A" />
              <div v-else class="common-prompt" style="background-color:#F56C6C" />
              <dict-tag :options="dict.type.status" :value="scope.row.status" />
            </span>
          </template>
        </el-table-column>
        <el-table-column
          v-if="columns[6].visible"
          label="创建时间"
          width="180"
          align="center"
          prop="createTime"
          show-overflow-tooltip
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="280" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              v-hasPermi="['system:user:edit']"
              size="mini"
              type="primary"
              plain
              @click="handleUpdate(scope.row)"
            >编辑</el-button>
            <el-button
              v-hasPermi="['system:user:resetPwd']"
              size="mini"
              type="primary"
              plain
              @click="handleResetPwd(scope.row)"
            >重置密码</el-button>
            <el-button
              v-hasPermi="['system:user:remove']"
              size="mini"
              type="danger"
              plain
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60" append-to-body class="user-dialog">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户姓名" prop="nickName">
              <el-input v-model="form.nickName" placeholder="请输入用户姓名" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机号码" prop="phonenumber">
              <el-input v-model="form.phonenumber" placeholder="请输入手机号码" maxlength="11" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="!form.userId">
          <el-col :span="12">
            <el-form-item label="用户账号" prop="userName">
              <el-input v-model="form.userName" :disabled="form.userId" placeholder="请输入用户账号" maxlength="30" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="用户密码" prop="password">
              <el-input
                v-model="form.password"
                placeholder="请输入用户密码"
                type="password"
                maxlength="20"
                auto-complete="new-password"
                show-password
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="归属部门" prop="deptIds">
              <template v-if="deptOptions.length <= 0 && this.$store.state.user.userId === form.userId">
                <treeselect
                  v-model="form.deptIds"
                  :options="deptFlatOptions"
                  :clearable="false"
                  searchable
                  multiple
                  flat
                  show-count
                  placeholder="请选择归属部门"
                  no-options-text="暂无数据"
                  no-results-text="暂无数据"
                  no-children-text="暂无数据"
                  disabled
                  @select="onSelect"
                  @open="openFun"
                  @deselect="onDeselect"
                />
              </template>
              <template v-else>
                <treeselect
                  v-model="form.deptIds"
                  :options="deptOptions"
                  :clearable="false"
                  searchable
                  multiple
                  flat
                  show-count
                  placeholder="请选择归属部门"
                  no-options-text="暂无数据"
                  no-results-text="暂无数据"
                  no-children-text="暂无数据"
                  @select="onSelect"
                  @open="openFun"
                  @deselect="onDeselect"
                />
              </template>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="默认部门" prop="deptId">
              <el-select v-model="form.deptId" placeholder="请选择默认部门">
                <el-option
                  v-for="item in deptFlatOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户性别">
              <el-select ref="selectSex" v-model="form.sex" placeholder="请选择性别">
                <el-option
                  v-for="dict in dict.type.sys_user_sex"
                  :key="dict.value"
                  :label="dict.label"
                  :value="dict.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" placeholder="请输入邮箱" maxlength="50" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="状态">
              <el-radio-group v-model="form.status">
                <el-radio v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.value">
                  {{ dict.label }}
                </el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="岗位" prop="postInfos">
              <el-cascader
                v-model="form.postInfos"
                :options="postOptions"
                :props="{ expandTrigger: 'hover', multiple: true }"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
      <el-upload
        ref="upload"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload.headers"
        :action="upload.url + '?updateSupport=' + upload.updateSupport"
        :disabled="upload.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :on-change="handleFileChange"
        :auto-upload="false"
        drag
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div slot="tip" class="el-upload__tip text-center">
          <div slot="tip" class="el-upload__tip">
            <el-checkbox v-model="upload.updateSupport" />
            是否更新已经存在的用户数据
          </div>
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size:12px;vertical-align: baseline;"
            @click="importTemplate"
          >下载模板
          </el-link>
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="upload.open = false">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 重置密码 -->
    <el-dialog title="重置密码" :visible.sync="defaultPassword.open" :destroy-on-close="true" width="400px" append-to-body>
      <el-form ref="resetPwdForm" :model="defaultPassword" :rules="resetPwdRules" label-width="100px">
        <el-form-item label="用户姓名" prop="nickName">
          <div>{{ defaultPassword.nickName }}</div>
        </el-form-item>
        <el-form-item label="用户账号" prop="nickName">
          <div>{{ defaultPassword.userName }}</div>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="defaultPassword.password" type="password" placeholder="请输入密码" maxlength="64" show-password />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="doResetPwd">确 定</el-button>
        <el-button @click="defaultPassword.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser, resetUserPwd, changeUserStatus, getDefaultPassword } from '@/api/system/user'
import { getPostsByDeptIds } from '@/api/system/post'
import { getToken } from '@/utils/auth'
import { treeselect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import store from '@/store'
import { decrypt, encrypt } from '@/utils/jsencrypt'
import { passwordValidator } from '@/utils/password'
import { getSysPassword } from '@/api/system/sys-password'
import { mapGetters } from 'vuex'
export default {
  name: 'User',
  dicts: ['sys_normal_disable', 'sys_user_sex', 'status'],
  components: { Treeselect },

  data() {
    const validatePost = (rule, value, callback) => {
      if (this.form.deptIds && this.form.deptIds.length) {
        if (this.form.postInfos && this.form.postInfos.length) {
          callback()
        } else {
          callback(new Error('岗位不能为空!'))
        }
      } else {
        callback()
      }
    }
    return {
      // 上传文件标志
      isFile: false,
      // 遮罩层
      loading: true,
      submitLoading: false,
      importLoading: false,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 用户表格数据
      userList: null,
      // 弹出层标题
      title: '',
      // 部门树选项
      deptOptions: [],
      // 部门扁平化选项
      deptFlatOptions: [],
      // 部门数据扁平化数据
      deptFlatMap: undefined,
      // 是否显示弹出层
      open: false,
      // 部门名称
      deptName: undefined,
      // 默认密码
      initPassword: undefined,
      // 日期范围
      dateRange: [],
      // 岗位选项
      postOptions: [],
      // 角色选项
      roleOptions: [],
      // 表单参数
      form: {
        deptIds: [],
        deptId: undefined,
        postInfos: []
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/system/user/importData'
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: undefined,
        phonenumber: undefined,
        status: undefined,
        deptId: undefined
      },
      // 列信息
      columns: [
        { key: 0, label: `用户编号`, visible: true },
        { key: 1, label: `用户账号`, visible: true },
        { key: 2, label: `用户姓名`, visible: true },
        { key: 3, label: `部门`, visible: true },
        { key: 4, label: `手机号码`, visible: true },
        { key: 5, label: `状态`, visible: true },
        { key: 6, label: `创建时间`, visible: true }
      ],
      // 表单校验
      rules: {
        userName: [
          { required: true, message: '用户账号不能为空', trigger: 'blur' },
          { min: 2, max: 20, message: '用户账号长度必须介于 2 和 20 之间', trigger: 'blur' }
        ],
        nickName: [
          { required: true, message: '用户姓名不能为空', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '用户密码不能为空', trigger: 'blur' },
          { required: true, validator: this.passwordValidator, trigger: 'blur' }
        ],
        email: [
          {
            type: 'email',
            message: '请输入正确的邮箱地址',
            trigger: ['blur', 'change']
          }
        ],
        phonenumber: [
          {
            pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
            message: '请输入正确的手机号码',
            trigger: 'blur'
          },
          { required: true, message: '手机号码不能为空', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '默认部门不能为空', trigger: 'change' }
        ],
        deptIds: [
          { required: true, message: '归属部门不能为空', trigger: 'change', type: 'array' }
        ],
        postInfos: [
          { required: true, validator: validatePost, type: 'array', message: '岗位不能为空', trigger: 'blur' }
        ],
        roleIds: [
          { required: true, message: '部门不能为空', trigger: 'change' }
        ],
        remark: [
          { max: 500, message: '最多可以输入500个字符', trigger: 'change' }
        ]
      },
      // 查询条件
      formOptions: [{
        label: '用户账号:',
        prop: 'userName',
        type: 'input',
        placeholder: '请输入用户账号'
      }, {
        label: '手机号码:',
        prop: 'phonenumber',
        type: 'input',
        placeholder: '请输入手机号码'
      }, {
        label: '状态:',
        prop: 'status',
        type: 'select',
        options: [],
        placeholder: '用户状态'
      }, {
        label: '创建时间:',
        prop: 'dateRange',
        type: 'slot'
      }],
      defaultPassword: {
        defaultVal: null,
        userId: null,
        userName: null,
        nickName: null,
        password: null,
        open: false
      },
      resetPwdRules: {
        password: [
          { required: true, message: '新密码不能为空', trigger: 'blur' },
          { required: true, validator: this.resetPasswordValidator, trigger: 'blur' }
        ]
      },
      pwdConfig: null
    }
  },
  computed: {
    ...mapGetters(['currentUser'])
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val)
    },
    'form.deptIds': {
      handler(newV, oldV) {
        if (newV) {
          this.deptFlatOptions = []
          newV.forEach(item => {
            if (this.deptFlatMap && this.deptFlatMap.get(item)) {
              this.deptFlatOptions.push(this.deptFlatMap.get(item))
            } else if (store.state.user.userId === this.form.userId) {
              let tempIndex
              for (tempIndex in this.form.depts) {
                if (this.form.depts[tempIndex].deptId === item) {
                  this.deptFlatOptions.push({
                    id: this.form.depts[tempIndex].deptId,
                    label: this.form.depts[tempIndex].deptName
                  })
                  break
                }
              }
            }
          })
          // 默认选择的第一个为默认部门
          if (this.deptFlatOptions.length) {
            // 如果当前用户有默认部门
            if (this.form.deptId) {
              // 如果选择的部门中不包含当前的默认部门
              if (newV.findIndex(id => id === this.form.deptId) === -1) {
                this.form.deptId = this.deptFlatOptions[0].id
              }
            } else {
              this.form.deptId = this.deptFlatOptions[0].id
            }
          }
        }
      },
      immediate: true
    }
  },
  created() {
    this.getList()
    this.getTreeselect()
  },
  mounted() {
    this.formOptions[2].options = this.dict.type.sys_normal_disable
    getDefaultPassword().then(res => {
      const pwd = decrypt(res.data)
      this.defaultPassword.defaultVal = pwd
      this.initPassword = pwd
    }).catch(err => {
      console.error('获取默认密码失败：', err)
    })
    this.loadPwdConfig()
  },
  methods: {
    loadPwdConfig() {
      if (this.currentUser.sysPassword) {
        this.pwdConfig = { ...this.currentUser.sysPassword }
      }
      if (this.pwdConfig == null) {
        getSysPassword().then(res => {
          this.pwdConfig = res.data
        }).catch(err => {
          this.pwdConfig == null
          console.error(err)
        })
      }
    },
    /** 查询用户列表 */
    getList() {
      this.loading = true
      listUser(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.userList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    openFun() {
      this.$refs.selectSex.blur()
    },
    // 归属部门选择后关闭事件
    onSelect() {
      this.$nextTick(() => {
        if (this.form.deptIds && this.form.deptIds.length > 0) {
          this.getPostOptions()
        }
      })
    },
    onDeselect(node) {
      this.$nextTick(() => {
        if (this.form.deptIds && this.form.deptIds.length > 0) {
          this.getPostOptions()
        } else {
          this.form.deptId = undefined
          this.postOptions = null
        }
      })
      if (this.form.postInfos) {
        const newPostInfos = []
        this.form.postInfos.forEach(p => {
          if (p[0] !== node.id) {
            newPostInfos.push(p)
          }
        })
        this.form.postInfos = newPostInfos
      }
    },
    getPostOptions(callBack) {
      getPostsByDeptIds(this.form.deptIds).then(res => {
        const deptPostMap = new Map()
        res.data.forEach(item => {
          item.value = item.postId
          item.label = item.postName
          let postsArray = deptPostMap.get(item.deptId)
          if (postsArray) {
            postsArray.push(item)
          } else {
            postsArray = []
            postsArray.push(item)
            deptPostMap.set(item.deptId, postsArray)
          }
        })
        const postOptions = []
        for (const k of deptPostMap.keys()) {
          const v = deptPostMap.get(k)
          const postOpt = { value: v[0].deptId, label: v[0].deptName }
          postOpt.children = v
          postOptions.push(postOpt)
        }
        this.postOptions = postOptions
        if (callBack) {
          callBack()
        }
      })
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data
        const deptFlatMap = new Map()
        this.flatDept(response.data, deptFlatMap)
        this.deptFlatMap = deptFlatMap
      })
    },
    flatDept(deptData, flatMap) {
      deptData.forEach(d => {
        flatMap.set(d.id, { id: d.id, label: d.label })
        if (d.children && d.children.length) {
          this.flatDept(d.children, flatMap)
        }
      })
    },
    // 筛选节点
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 节点单击事件
    handleNodeClick(data) {
      this.queryParams.deptId = data.id
      this.handleQuery()
    },
    // 用户状态修改
    handleStatusChange(row) {
      const text = row.status === '0' ? '启用' : '停用'
      this.$modal.confirm('确认要"' + text + '""' + row.userName + '"用户吗？').then(function() {
        return changeUserStatus(row.userId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        userId: undefined,
        deptId: undefined,
        userName: undefined,
        nickName: undefined,
        password: undefined,
        phonenumber: undefined,
        email: undefined,
        sex: undefined,
        status: '0',
        remark: undefined,
        postInfos: undefined,
        roleIds: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery(data) {
      this.queryParams = Object.assign(this.queryParams, data)
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.userId)
      this.names = selection.map(item => item.userName)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.getTreeselect()
      getUser().then(response => {
        const extData = response.extData || {}
        this.roleOptions = extData.roles || response.roles
        this.open = true
        this.reset()
        this.submitLoading = false
        this.title = '添加用户'
        this.form.password = this.initPassword
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.getTreeselect()
      const userId = row.userId || this.ids
      getUser(userId).then(response => {
        this.form = response.data
        const extData = response.extData || {}
        this.postOptions = extData.posts || response.posts
        this.roleOptions = extData.roles || response.roles
        if (this.form.deptIds && this.form.deptIds.length) {
          this.getPostOptions(() => {
            if (extData.posts && extData.posts.length) {
              const postInfos = []
              extData.posts.forEach(p => {
                postInfos.push([p.deptId, p.postId])
              })
              this.form.postInfos = postInfos
            }
          })
        }
        this.form.roleIds = extData.roleIds || response.roleIds
        this.open = true
        this.submitLoading = false
        this.title = '修改用户'
        this.form.password = ''
      })
    },
    /** 重置密码按钮操作 */
    handleResetPwd(row) {
      this.defaultPassword.userId = row.userId
      this.defaultPassword.userName = row.userName
      this.defaultPassword.nickName = row.nickName
      this.defaultPassword.password = this.defaultPassword.defaultVal
      this.defaultPassword.open = true
    },
    doResetPwd() {
      this.$refs.resetPwdForm.validate(valid => {
        if (valid) {
          resetUserPwd(this.defaultPassword.userId, encrypt(this.defaultPassword.password)).then(response => {
            this.$modal.msgSuccess('修改成功，新密码是：' + this.defaultPassword.password)
            this.defaultPassword.open = false
          })
        }
      })
    },
    /** 分配角色操作 */
    handleAuthRole: function(row) {
      const userId = row.userId
      this.$router.push('/system/user-auth/role/' + userId)
    },
    /** 提交按钮 */
    submitForm: function() {
      this.submitLoading = true
      this.$refs['form'].validate(valid => {
        if (valid) {
          const posts = []
          // 处理form数据
          if (this.form.postInfos) {
            this.form.postInfos.forEach(p => {
              posts.push({ deptId: p[0], postId: p[1] })
            })
          }
          this.form.posts = posts
          if (this.form.userId) {
            updateUser(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            }).catch(err => {
              this.submitLoading = false
              console.error(err)
            })
          } else {
            const parse = JSON.parse(JSON.stringify(this.form))
            parse.password = encrypt(parse.password)
            addUser(parse).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            }).catch(err => {
              this.submitLoading = false
              console.error(err)
            })
          }
        } else {
          this.submitLoading = false
        }
      })
    },
    /** 批量删除 */
    handleDeleteAll() {
      if (this.ids.length > 0) {
        this.$modal.confirm('是否确认删除用户账号为"' + this.names + '"的数据项？').then(() => {
          return delUser(this.ids).then(() => {
            this.getList()
            this.$modal.msgSuccess('删除成功')
          }).catch(() => {
          })
        })
      } else {
        this.$message.warning('未选中数据')
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal.confirm('是否确认删除用户账号为"' + row.userName + '"的数据项？').then(function() {
        return delUser(row.userId)
      }).then(() => {
        this.getList()
        this.$modal.msgSuccess('删除成功')
      }).catch(() => {
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/user/export', {
        ...this.queryParams
      }, `user_${new Date().getTime()}.xlsx`)
    },
    /** 导入按钮操作 */
    handleImport() {
      this.importLoading = false
      this.isFile = false
      this.upload.title = '用户导入'
      this.upload.open = true
    },
    /** 下载模板操作 */
    importTemplate() {
      this.download('system/user/importTemplate', {}, `user_template_${new Date().getTime()}.xlsx`)
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false
      this.upload.isUploading = false
      this.$refs.upload.clearFiles()
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + '</div>', '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 文件上传发生变化时调用
    handleFileChange(response, file, fileList) {
      if (file.length !== 0) {
        this.isFile = true
        const type = file[0].raw.type
        if (type !== 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' && type !== 'application/vnd.ms-excel') {
          this.$message.error('上传的文件类型错误')
          this.isFile = false
          this.$refs.upload.clearFiles()
        }
      }
    },
    // 提交上传文件
    submitFileForm() {
      if (this.isFile) {
        this.$refs.upload.submit()
      } else {
        this.$message.warning('请选择上传文件')
      }
    },
    passwordValidator(rule, value, callback, source, options) {
      passwordValidator(this.form.userName, this.pwdConfig, rule, value, callback)
    },
    resetPasswordValidator(rule, value, callback, source, options) {
      passwordValidator(this.defaultPassword.userName, this.pwdConfig, rule, value, callback)
    }
  }
}
</script>
<style lang="scss" scoped>
.user {
  display: flex;
  height: 100%;

  .tree {
    height: 100%;
    width: 200px;
    overflow: auto;

    .search {
      margin-bottom: 20px;
    }

    .content {
      height: calc(100% - 52px);
      overflow: auto;
    }
  }

  .list {
    height: 100%;
    width: calc(100% - 210px);
    margin-left: 10px;
  }
}
</style>
